package cn.ciis.basic.plugin;

import cn.ciis.basic.TioHandlerInterface;
import cn.ciis.server.handler.BusinessHandler;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ClassUtil;
import com.jfinal.aop.Aop;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class CiisHandlerFactory {

    public static CiisHandler getHandler(String packageName) {

        if(StrKit.isBlank(packageName)){
            return Aop.get(BusinessHandler.class);
        }
        TimeInterval timer = DateUtil.timer();

        String[] packges = packageName.split(";");

        List<Ret> list = CollUtil.newArrayList();
        for (String packge : packges) {
            Set<Class<?>> classSet = ClassUtil.scanPackageByAnnotation(packge, TioHandlerInterface.class);
            Iterator<Class<?>> iterator = classSet.iterator();

            Ret ret =null;
            while (iterator.hasNext()){
                Class<?> next =  iterator.next();
                ret = Ret.create("order",next.getAnnotation(TioHandlerInterface.class).order());
                ret.set("handler", Aop.get(next));
                list.add(ret);
            }
        }

        CollUtil.sort(list, (a, b) -> a.getInt("order") - b.getInt("order"));

        CiisHandler result = null;

        for (int i=list.size()-1; i>=0; i--) {
            CiisHandler temp = list.get(i).getAs("handler");

            if (result != null) {
                temp.next = result;
            }
            result = temp;
        }
        LogKit.info("Tio Handler扫描总共耗时:{}毫秒",timer.interval());
        return  result;
    }
}
